package com.emo.wowoblog.controller;

import com.emo.wowoblog.vo.HttpResult;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * 使用第一种方案生成 验证码
 */
@RestController
@RequestMapping("/commons")
public class KaptchaController {

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @GetMapping("/createRandomCodeImage")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setDateHeader("Expires", 0);// 禁止server端缓存
        // 设置标准的 HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // 设置IE扩展 HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");// 设置标准 HTTP/1.0 不缓存图片
        response.setContentType("image/jpeg");// 返回一个 jpeg 图片，默认是text/html(输出文档的MIMI类型)
        String capText = defaultKaptcha.createText();// 为图片创建文本
        // 将文本保存在session中。这里使用自定义名称，注意以后校验时要使用该名称获取Session中的验证码
        request.getSession().setAttribute(KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = defaultKaptcha.createImage(capText); // 创建带有文本的图片
        ServletOutputStream out = response.getOutputStream();
        // 图片数据输出
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    @PostMapping("/checkVerificationCode")
    public static Map<String, Object> checkVerificationCode(@RequestParam(value = "code") String verificationCode, HttpServletRequest httpServletRequest) {
        String verificationCodeIn = (String) httpServletRequest.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        httpServletRequest.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if (StringUtils.hasText(verificationCodeIn) || !verificationCodeIn.equals(verificationCode)) {
            return HttpResult.fail("验证码错误，或已失效");
        }
        return HttpResult.success(verificationCode);
    }
}